package com.huluobo.jetpackkotlindemo2006a.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 * Created by lc on 2023/2/22.
 * PagingSource<Int, Repo>() Int代表页数的类型,Repo代表数据item的类型
 */
class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, Repo>() {
    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val page = params.key ?: 1 //当前的页码
            val pageSize = params.loadSize//当前页面中item的数量
            val repoResponse = apiService.searchRepos(page, pageSize) //发起网络请求的返回
            val repoItems = repoResponse.items //请求返回的bean类集合
            val prevKey = if (page > 1) page - 1 else null //代表向前翻页的页码
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null //向后翻页的页码
            LoadResult.Page(repoItems, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}